package com.mdd.front.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.wxpay.bean.notify.SignatureHeader;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.mdd.common.aop.NotLogin;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.enums.ClientEnum;
import com.mdd.common.plugin.wechat.WxPayDriver;
import com.mdd.common.util.RequestUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IExpressDeliveryService;
import com.mdd.front.validate.PayVipValidate;
import com.mdd.front.vo.fast.CashbackGoldCoinDto;
import com.mdd.front.vo.fast.FastArticleTypeVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/expressDelivery")
@Api(tags = "快递相关API")
public class ExpressDeliveryController {

	@Autowired
	private IExpressDeliveryService expressDeliveryService;

	@NotLogin
	@PostMapping("/fastType")
	@ApiOperation(value="快递分类")
	public AjaxResult<Object> fastType(@RequestBody String body) {
		Map<String, Object> retMap = expressDeliveryService.fastType();
		retMap.put("body", body);
		return AjaxResult.success(retMap);
	}
	
	@NotLogin
	@PostMapping("/kdCashbackGoldCoin")
	@ApiOperation(value="快递下单返金币")
	public AjaxResult<Object> kdCashbackGoldCoin(@RequestBody CashbackGoldCoinDto dto) {
		if(null == dto) {
			return AjaxResult.failed("请选择用户");
		}
		if(null == dto.getUserId()) {
			return AjaxResult.failed("请选择用户");
		}
		if(StringUtils.isEmpty(dto.getCode())) {
			return AjaxResult.failed("快递公司不存在");
		}
		expressDeliveryService.kdCashbackGoldCoin(dto);
		return AjaxResult.success();
	}

	@NotLogin
	@GetMapping("/fastActicleType")
	@ApiOperation(value="快递物品分类")
	public AjaxResult<List<FastArticleTypeVo>> fastActicleType() {
		List<FastArticleTypeVo> list = expressDeliveryService.fastActicleType();
		return AjaxResult.success(list);
	}

	@PostMapping("/payOrder")
	@ApiOperation("支付订单")
	public AjaxResult<Object> payOrder(@Validated @RequestBody PayVipValidate requestObj) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		if(StringUtils.isEmpty(requestObj.getKuaidiNum())) {
			return AjaxResult.failed("快递订单号为空");
		}
		Integer terminal = LikeFrontThreadLocal.getTerminal();
		return expressDeliveryService.payOrder(requestObj, userId,terminal);
	}
	
	@GetMapping("/noticeMessage")
	@ApiOperation(value="快递通知消息")
	public AjaxResult<Object> noticeMessage() {
		System.out.println("请求前缀："+RequestUtils.uri());
		return expressDeliveryService.noticeMessage();
	}
	
	/**
	 * 用于支付宝回调
	 */
    @NotLogin
	@RequestMapping(value = "/notifyFromAlipay", method = { RequestMethod.POST, RequestMethod.GET })
	public String notifyFromAlipay(HttpServletRequest httpServletRequest) {
		System.out.println("进入支付宝回调============");
		Map<String, String> params = new HashMap<>();
		Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8",token);
			params.put(name, valueStr);
		}
		return expressDeliveryService.notifyFromAlipay(params);
	}
    
    
    @NotLogin
	@PostMapping("/notifyFromMnpWxpay")
	@ApiOperation("微信小程序支付回调")
	public AjaxResult<Object> notifyMnp(@RequestBody String jsonData, HttpServletRequest request) throws WxPayException {
		// 构建签名
		SignatureHeader signatureHeader = new SignatureHeader();
		signatureHeader.setSignature(request.getHeader("wechatpay-signature"));
		signatureHeader.setNonce(request.getHeader("wechatpay-nonce"));
		signatureHeader.setSerial(request.getHeader("wechatpay-serial"));
		signatureHeader.setTimeStamp(request.getHeader("wechatpay-timestamp"));

		// 解密数据
		WxPayService wxPayService = WxPayDriver.handler(ClientEnum.MNP.getCode());
		WxPayOrderNotifyV3Result.DecryptNotifyResult notifyResult = wxPayService.parseOrderNotifyV3Result(jsonData, signatureHeader).getResult();

		// 取出数据
		String transactionId = notifyResult.getTransactionId();
		String outTradeNo = notifyResult.getOutTradeNo();
		String attach =  notifyResult.getAttach();

		// 处理回调
		expressDeliveryService.handlePaidNotify(attach, outTradeNo, transactionId);
		return AjaxResult.success();
	}
    
    /**
	 * 用于微信回调
	 */
    @NotLogin
	@RequestMapping(value = "/notifyFromWxpay", method = { RequestMethod.POST, RequestMethod.GET })
	public String notifyFromWxpay(HttpServletRequest httpServletRequest) {
		InputStream is = null;
		String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		try {
			is = httpServletRequest.getInputStream();
			// 将InputStream转换成String
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			xmlBack = expressDeliveryService.notifyFromWxpay(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return xmlBack;
	}
    
    /**
	 * 	微信退款回调
	 * @param httpServletRequest
	 * @return
	 */
    @NotLogin
	@RequestMapping(value = "/notifyFromWxpayRefund", method = { RequestMethod.POST, RequestMethod.GET })
	public String notifyFromPayNotify(HttpServletRequest request) {
		return expressDeliveryService.notifyFromWxpayRefund(request);
	}
    
    
    @NotLogin
    @PostMapping("/orderRefund")
	@ApiOperation("快递订单退款")
	public AjaxResult<Object> orderRefund(@Validated @RequestBody PayVipValidate requestObj) {
		//Integer userId = LikeFrontThreadLocal.getUserId();
		if(StringUtils.isEmpty(requestObj.getKuaidiNum())) {
			return AjaxResult.failed("快递订单号为空");
		}
		return expressDeliveryService.orderRefund(requestObj);
	}

}
